//
//  MTNativeStoreViewController.m
//  ebook
//
//  Created by mt on 17/1/9.
//  Copyright © 2017年 Moton. All rights reserved.
//

#import "MTNativeStoreViewController.h"
#import "NativeStoreOptionsCell.h"
#import "NativeStoreCell.h"
#import "NativeOrderlistModel.h"
#import "NativeStoreOptionsModel.h"
#import "EbookNetRequest.h"
#import "MTStoreDetailViewController.h"
#import "MJRefresh.h"
#import "ReaderGlobalModel.h"
#import "NSString+Time.h"
#import "SearachViewController.h"

@interface MTNativeStoreViewController ()<UITableViewDelegate, UITableViewDataSource,NativeStoreOptionsCellDelegate>
{
    NSInteger sortid;
    NSInteger fullFlag;
    
    NSInteger itemcount;
    NSInteger pagecount;
    NSInteger pagecurrent;
    NSString *order;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *optionsDataArray;
@property (nonatomic, assign) BOOL optionCellIsClosed;
@property (nonatomic, strong) UIButton *scrollTopBtn;

@end

@implementation MTNativeStoreViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationItem.title = @"书城";
    self.view.backgroundColor = MTColor(245, 245, 245, 1);
    _dataArray = [NSMutableArray array];
    
    [self.view addSubview:self.tableView];
    sortid = -1;
    fullFlag = 1;
    
    pagecurrent = 1;
    pagecount = 1;
    order = @"visit";
    [self setBarItem];
    [self getOptionsData];
    [self bindRefresh];
}

-(void)setBarItem{
    
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBook:)];
    searchItem.tintColor = MTConfigColor(@"MTNavigationBar_rightItem_Color");
    self.navigationItem.rightBarButtonItem = searchItem;
}

#pragma mark - searchBook
- (void)searchBook:(id)sender
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.navigationItem.rightBarButtonItem.enabled = YES;
    });
    
    SearachViewController *searchVc = [[SearachViewController alloc] init];
    [self.navigationController pushViewController:searchVc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)bindRefresh {

    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self getBook];
    }];
}

- (void)reloadView {
    
    [self hideFailedView];
    [self showHud];
    [self getOptionsData];
}

- (void)getOptionsData {
    
    [self showHud];
    __block MTNativeStoreViewController *weakSelf = self;
    /*
    [EbookNetRequest getSeekOptionsSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        
        NSMutableArray *tempArray = [NSMutableArray array];
        NSArray *array = dict[@"resp"];
        for (NSDictionary *d in array) {
            NativeStoreOptionsModel *model = [[NativeStoreOptionsModel alloc] initWithDictionary:d];
            [tempArray addObject:model];
        }
        [weakSelf filterOptionData:tempArray];
        [weakSelf hideHud];
        [weakSelf.tableView reloadData];
        //搜索条件数据获取成功， 获取列表数据； 列表数据中sortname需要从搜索条件中获取
        [weakSelf getBook];
    } failed:^(int stateCode, NSString *failMsg) {
        MTLog(@"%@", failMsg);
        [self showFailedView];
    }];*/
}

- (void)filterOptionData:(NSArray *)array {
    
    _optionsDataArray = [NSMutableArray array];
    for (NativeStoreOptionsModel *model in array) {
        if ([model.parentid intValue]==0) {
            [_optionsDataArray addObject:model];
        }
    }
}

- (void)getBook {
    
    if (pagecurrent>pagecount) return;
    
    [self showHud];
    /*
    [EbookNetRequest getNativeStoreWithPage:pagecurrent sort:sortid fullflag:fullFlag order:order success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        
        NSDictionary *resp = dict[@"resp"];
        pagecount = [resp[@"Pagecount"] integerValue];
        pagecurrent = [resp[@"Pagecurr"] integerValue]+1;
        
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dic in resp[@"Items"]) {
            NativeOrderlistModel *model = [[NativeOrderlistModel alloc] initWithDictionary:dic];
            model.lastupdate = [@"" interceptTimeStampFromStr:model.lastupdate];
            model.sortname = [self getSortnameWithSortid:model.sortid];
            [tempArray addObject:model];
        }
        
        [_dataArray addObjectsFromArray:tempArray];
        [_tableView reloadData];
        [_tableView.mj_footer endRefreshing];
        [self hideHud];

    } failed:^(int stateCode, NSString *failMsg) {
        [self hideHud];
        [self showFailedView];
    }];*/
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight-49) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorColor = MTColor(243, 243, 243, 1.0);
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_optionCellIsClosed) {
        if (section==0) {
            return _optionsDataArray?1:0;
        } else {
            return _dataArray.count;
        }
    } else {
        if (section==0) {
            return _optionsDataArray?(kIsShowFullState==1?3:2):0;
        } else {
            return _dataArray.count;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            return 44.0;
        } else if (indexPath.row==1) {
            return 44*(_optionsDataArray.count%4);
        } else {
            return 44.0;
        }
    } else {
        return 135.0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0) {
        return CGFLOAT_MIN;
    }
    return 10.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section==0) {
        static NSString *idenrifier = @"cellSection0";
        NativeStoreOptionsCell *cell = [tableView dequeueReusableCellWithIdentifier:idenrifier];
        if (!cell) {
            cell = [[NativeStoreOptionsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idenrifier indexOfRow:indexPath.row optionsArray:indexPath.row==1?_optionsDataArray:nil];
        }
        cell.delegate = self;
        return cell;
    } else {
        static NSString *identifier = @"cellSection1";
        NativeStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[NativeStoreCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        
        NativeOrderlistModel *model = _dataArray.count>indexPath.row?_dataArray[indexPath.row]:nil;
        cell.model = model;
        return cell;
    }
}

#pragma mark - SeekOptionsCellDelegate
- (void)nativeStoreOptionsCell:(NativeStoreOptionsCell *)cell cellIsClosed:(BOOL)closed {
    
    _optionCellIsClosed = closed;
    [_tableView reloadData];
}

- (void)nativeStoreOptionsCell:(NativeStoreOptionsCell *)cell hotSelectAtIndex:(NSInteger)index {
    
    if (index==-1)order = @"visit"; //热门书籍
    if (index==0) order = @"new";   //最新上架
    if (index==1) order = @"vote";  //评分最高
    
    [self resetSearchOptions];
}

- (void)nativeStoreOptionsCell:(NativeStoreOptionsCell *)cell selectWithModel:(NativeStoreOptionsModel *)model {
    
    sortid =  model?[model.sortid intValue]:-1;
    [self resetSearchOptions];
}

- (void)nativeStoreOptionsCell:(NativeStoreOptionsCell *)cell fullSelectAtIndex:(NSInteger)index {
    
    fullFlag = index;
    [self resetSearchOptions];
}

- (void)resetSearchOptions {
 
    pagecurrent = 1;
    pagecount = pagecurrent+2;
    [_dataArray removeAllObjects];
    [self getBook];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section==0) return;

    MTStoreDetailViewController *resultVc = [[MTStoreDetailViewController alloc] init];
    NativeOrderlistModel *model = _dataArray[indexPath.row];
    resultVc.title = model.bookname;
    resultVc.model = model;
    resultVc.order = order;
    [self.navigationController pushViewController:resultVc animated:YES];
}

- (NSString *)getSortnameWithSortid:(NSString *)sortid1 {
    
    __block NSString *sortname;
    [_optionsDataArray enumerateObjectsUsingBlock:^(NativeStoreOptionsModel *obj, NSUInteger idx, BOOL * stop) {
        
        if ([obj.sortid integerValue]==[sortid1 integerValue]) {
            sortname = obj.name;
            *stop = YES;
        }
    }];
    return sortname;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.y<=0) {
        [scrollView setContentOffset:CGPointZero];
    }
}

//返回顶部按钮
- (UIButton *)scrollTopBtn {
    if (!_scrollTopBtn) {
        _scrollTopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _scrollTopBtn.frame = CGRectMake(MTScreenW-55, MTScreenH-150, 35, 35);
        [_scrollTopBtn setImage:[UIImage imageNamed:@"scrollToTop"] forState:UIControlStateNormal];
        _scrollTopBtn.backgroundColor = [UIColor lightTextColor];
        [_scrollTopBtn addTarget:self action:@selector(scrollTopBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _scrollTopBtn;
}

- (void)scrollTopBtnClick {
    
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}


@end
